package cn.itcast.bos.before.service.impl;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.core.MediaType;

import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

















import cn.itcast.bos.before.utils.MyServletContext;
import cn.itcast.bos.domain.delivery.Promotion;
import cn.itcast.bos.domain.utils.PageBean;
import freemarker.template.Configuration;
import freemarker.template.Template;


@Service
@Scope("prototype")
public class PromotionServiceImpl{
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private MyServletContext myServletContext;
	public void writeDataToHtml() throws Exception{
		//获取bos_manager中的promotion数据
		PageBean<Promotion> pageBean = WebClient.create("http://localhost:8080/bos_management/bos_mgr/bos/promotion/all")
				.accept(MediaType.APPLICATION_JSON).
				get(PageBean.class);
		List<Promotion> content = pageBean.getContent();
		String realPath = myServletContext.getServletContext().getRealPath("/promotion");
		for (Promotion promotion : content) {
			Integer id = promotion.getId();
			File file=new File(realPath+"/"+id+".html");
			if(!file.exists()){
				String ip="http://localhost:8080";
				//获取freemarker的Configuration
				Configuration configuration=new Configuration(Configuration.VERSION_2_3_22);
				//设置模板的文件夹位置
				configuration.setDirectoryForTemplateLoading(new File(myServletContext.getServletContext().getRealPath("/WEB-INF/templates")));
				//获取模板
				Template template = configuration.getTemplate("promotion_detail.ftl");
				Map<String,Object> map=new HashMap<String, Object>();
				String description = promotion.getDescription();
				description=description.replaceAll("/bos_management", ip+"/bos_management");
				promotion.setDescription(description);
				String titleImg=promotion.getTitleImg();
				titleImg=titleImg.replaceAll("/bos_management", ip+"/bos_management");
				promotion.setTitleImg(titleImg);
				System.out.println(promotion);
				//将数据对象封装到map集合中
				map.put("promotion", promotion);
				//已流的形式将map 中的数据写到静态页面中
				template.process(map, new OutputStreamWriter(new FileOutputStream(file),"utf-8"));
			}
		}
	}
}
